from django.conf import settings
from django.core.mail import send_mail
from django_redis import get_redis_connection
from rest_framework import serializers
from celery_tasks.email.tasks import send_verfiy_email
from goods.models import SKU
from .models import User, Address


class RegisterUserSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(min_length=8, max_length=20, label='确认密码', write_only=True)
    sms_code = serializers.CharField(min_length=6 , max_length=6 , label='短信验证码', write_only=True)
    allow = serializers.CharField(label='协议', write_only=True)
    token = serializers.CharField(label='jwt口令', read_only=True)

    class Meta:
        model = User
        fields = ("id","username","password","password2","mobile","sms_code","allow","token")
        read_only_fields = ("id",)
        extra_kwargs ={
            "password": {
                "min_length": 8,
                "max_length": 20,
                "write_only": True
            }
        }

    def validate_allow(self, value):

        if value !='true':
            raise serializers.ValidationError('必须同意协议')

        return  value

    #校验密码,短信
    def validate(self, attrs):

        sms_code = attrs["sms_code"]
        mobile = attrs["mobile"]

        if attrs["password"] != attrs["password2"]:
            raise serializers.ValidationError("两次密码不相等")

        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s" % mobile)

        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码已经过期")

        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码填写错误")

        return attrs

    #重写create,使用系统的方法给密码加密
    def create(self, validated_data):
        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]

        user = super(RegisterUserSerializer, self).create(validated_data)

        user.set_password(validated_data["password"])
        user.save()

        #设置jwt
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        return user

class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User

        fields = ("id","username","mobile","email","email_active")

class EmailSendSerializer(serializers.Serializer):
    email = serializers.EmailField(label='邮箱')

    def update(self, instance, validated_data):
        email = validated_data['email']

        instance.email = email

        instance.save()
        verfiy_url = instance.generate_verfiy_url()
        send_verfiy_email.delay(verfiy_url, email)  # 使用celery发送
        # send_mail(subject="请点击验证,来自美多商城",
        #           message = verfiy_url,
        #           from_email=settings.EMAIL_FROM,
        #           recipient_list=[email])
        return validated_data

class AddressSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省id')
    city_id = serializers.IntegerField(label='市id')
    district_id = serializers.IntegerField(label='区id')

    class Meta:
        model = Address

        exclude = ("user","is_deleted","create_time","update_time")


    def create(self, validated_data):
        validated_data['user'] = self.context['request'].user

        return super(AddressSerializer,self).create(validated_data)

class AddressTitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address

        fields = ("title",)


class UserBrowerHistorySerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1, label="商品编号")

    # 1,单字段校验
    def validate_sku_id(self, value):
        # 1,通过sku_id获取sku对象
        try:
            sku = SKU.objects.get(id=value)
        except Exception as e:
            raise serializers.ValidationError("商品不存在")

        # 2,返回
        return value

    # 2,重写create方法,需要保存记录到redis中
    def create(self, validated_data):
        # 1,获取sku_id
        sku_id = validated_data.get("sku_id")
        user = self.context["request"].user

        # 2,获取redis对象
        redis_conn = get_redis_connection("history")

        # 3,去重
        redis_conn.lrem("history_%s" % user.id, 0, sku_id)

        # 4,存储
        redis_conn.lpush("history_%s" % user.id, sku_id)

        # 5,截取5条
        redis_conn.ltrim("history_%s" % user.id, 0, 4)

        # 6,返回
        return validated_data